package org.edu.modules.base.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.edu.modules.base.entity.*;
import org.edu.modules.base.mapper.VeBaseSysMenuMapper;
import org.edu.modules.base.mapper.VeBaseSysRoleMenuMapper;
import org.edu.modules.base.service.IVeBaseSysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: 陈炜凡
 * @Description: TODO
 * @DateTime: 2021/12/13 16:47
 */
@Service
public class VeBaseSysMenuServiceImpl extends ServiceImpl<VeBaseSysMenuMapper, VeBaseSysMenu> implements IVeBaseSysMenuService {

    @Autowired
    private VeBaseSysMenuMapper veBaseSysMenuMapper;
    @Autowired
    private VeBaseAppManageServiceImpl veBaseAppManageServiceImpl;
    @Autowired
    private VeBaseSysRoleMenuServiceImpl veBaseSysRoleMenuServiceImpl;
    @Autowired
    private VeBaseSysRoleMenuMapper veBaseSysRoleMenuMapper;


    @Override
    public List<Map<String, Object>> getSysMenuTreeList(String id) {
        List<Map<String, Object>> rootList = this.veBaseSysMenuMapper.getRootList(id);
        List<Map<String, Object>> bodyList = this.veBaseSysMenuMapper.getBodyList(id);
        if (bodyList != null && !bodyList.isEmpty()) {
            Map<String, String> map = new HashMap<>();
            rootList.forEach(menu -> getChild(menu, map, id));
            return rootList;
        }
        return null;
    }

    @Override
    public List<JSONObject> getAllSysMenuTreeList(String userId,String isEnable) {

        //1、树状菜单
        List<JSONObject> treeList = new ArrayList<>();
        //1、根据获取到的userId工号查询有权限的系统信息
        List<VeBaseAppManage> veBaseAppManageList = veBaseAppManageServiceImpl.getAppManageAllListByUserId(userId,isEnable);
        Map<String, Object> map = new HashMap<>();
        for (VeBaseAppManage veBaseAppManage : veBaseAppManageList) {//子系统
            JSONObject sysJsonObject = new JSONObject();
            sysJsonObject.put("name",veBaseAppManage.getAppName());
//            jsonObject.put("path","");
            //获取子系统下有权限的所有菜单
            List<Map<String ,Object>> list = veBaseSysRoleMenuServiceImpl.getSysRoleMenuListByUserIdAppIdPid(userId,veBaseAppManage.getId(),null);
            List<JSONObject> sysChildList = new ArrayList<>();//子系统的下级
            for (Map<String ,Object> menu : list) {
                if (Integer.parseInt(menu.get("pid")+"") < 0 ){//子系统下根目录
                    JSONObject rootMenu = new JSONObject();
                    rootMenu.put("name",menu.get("text"));
                    rootMenu.put("path",menu.get("url"));
                    //筛选根目录的子集菜单
                    getChild(rootMenu,list,Integer.parseInt(menu.get("id")+""));
                    sysChildList.add(rootMenu);
                }
            }
            sysJsonObject.put("children",sysChildList);

            treeList.add(sysJsonObject);//整合系统菜单
        }
        return treeList;
    }
    public Integer addSysMenu(VeBaseSysMenu veBaseSysMenu) {
        return this.veBaseSysMenuMapper.addSysMenu(veBaseSysMenu);
    }

    public VeBaseSysMenu getSysMenuByPid(Integer pid) {
        return this.veBaseSysMenuMapper.getSysMenuByPid(pid);
    }

    public int deleteByAppId(String appId) {
        return this.veBaseSysMenuMapper.deleteByAppId(appId);
    }

    @Override
    public List<VeBaseSysMenu> getAllListTree(String appId) {
        List<VeBaseSysMenu> veBaseSysMenus = veBaseSysMenuMapper.selectList(new LambdaQueryWrapper<VeBaseSysMenu>().eq(VeBaseSysMenu::getAppId, appId));
        if (veBaseSysMenus.size() > 0) {
            // 构造树，根节点的 parentId 应该是 -id
            return buildTree(veBaseSysMenus);
        }
        return Collections.emptyList();
    }

    @Override
    public List<VeBaseSysMenu> getSysMenuTreeListEnabled(String appId) {
        return getSysMenuTreeListIfEnabled(appId);
    }

    public List<VeBaseSysMenu> getSysMenuTreeListIfEnabled(String appId) {
        List<VeBaseSysMenu> veBaseSysMenus = veBaseSysMenuMapper.selectList(new LambdaQueryWrapper<VeBaseSysMenu>().eq(VeBaseSysMenu::getAppId, appId)
                .eq(VeBaseSysMenu::getStatus, 1));
        if (veBaseSysMenus.size() > 0) {
            // 构造树，根节点的 parentId 应该是 -id
            return buildTree(veBaseSysMenus);
        }
        return Collections.emptyList();
    }

    @Override
    public List<VeBaseSysMenu> getRoleSysMenuTreeListEnabled(String appId, String roleId) {
        if (roleId.equals("6")){
            //系统管理员
            return getSysMenuTreeListIfEnabled(appId);
        }
        List<VeBaseSysRoleMenu> list= veBaseSysRoleMenuMapper.selectList(new LambdaQueryWrapper<VeBaseSysRoleMenu>()
                .eq(VeBaseSysRoleMenu::getRoleId, roleId)
                .eq(VeBaseSysRoleMenu::getAppId, appId));
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<VeBaseSysMenu> veBaseSysMenus = veBaseSysMenuMapper.selectList(new LambdaQueryWrapper<VeBaseSysMenu>().eq(VeBaseSysMenu::getAppId, appId)
                .eq(VeBaseSysMenu::getStatus, 1)
                .in(VeBaseSysMenu::getId,list.stream().map(VeBaseSysRoleMenu::getMenuId).toArray()));
        if (veBaseSysMenus.size() > 0) {
            // 构造树，根节点的 parentId 应该是 -id
            return buildTree(veBaseSysMenus);
        }
        return Collections.emptyList();
    }

    private List<VeBaseSysMenu> buildTree(List<VeBaseSysMenu> menus) {
        List<VeBaseSysMenu> treeMenus = new ArrayList<>();
        Map<Integer, VeBaseSysMenu> menuMap = new HashMap<>();

        // 将所有菜单放入 map 中，方便查找
        for (VeBaseSysMenu menu : menus) {
            menuMap.put(menu.getId(), menu);
        }

        // 找到根节点
        for (VeBaseSysMenu menu : menus) {
            if (menu.getPid() != null && menu.getPid().equals(-menu.getId())) {
                // 如果找到根节点，递归构造子节点
                List<VeBaseSysMenu> children = buildChildren(menuMap, menu.getId());
                menu.setChildren(children);
                treeMenus.add(menu);
            }
        }
        return treeMenus;
    }

    private List<VeBaseSysMenu> buildChildren(Map<Integer, VeBaseSysMenu> menuMap, Integer parentId) {
        List<VeBaseSysMenu> children = new ArrayList<>();
        for (VeBaseSysMenu menu : menuMap.values()) {
            if (menu.getPid() != null && menu.getPid().equals(parentId)) {
                List<VeBaseSysMenu> subChildren = buildChildren(menuMap, menu.getId());
                menu.setChildren(subChildren);
                children.add(menu);
            }
        }
        return children;
    }

    public void getChild(Map<String, Object> menu, Map<String, String> map, String id) {
        List<Map<String, Object>> bodyList = this.veBaseSysMenuMapper.getBodyList(id);
        List<Map<String, Object>> childList = new ArrayList<>();
        bodyList.stream().filter(c -> !map.containsKey(c.get("id"))).filter(c -> c.get("pid").toString().equals(menu.get("id").toString()))
                .forEach(c -> {
                    map.put(c.get("id").toString(), c.get("pid").toString());
                    getChild(c, map, id);
                    childList.add(c);
                });
        menu.put("childList", childList);
    }
    public void getChild(JSONObject menu, List<Map<String ,Object>> list,Integer id) {
        List<JSONObject> childList = new ArrayList<>();
        for (Map<String ,Object> childrenMenu : list) {
            if (Integer.parseInt(childrenMenu.get("pid")+"")==id){
                JSONObject childMenuJsonobject = new JSONObject();
                childMenuJsonobject.put("name",childrenMenu.get("text"));
                childMenuJsonobject.put("path",childrenMenu.get("url"));
                childList.add(childMenuJsonobject);
                getChild(childMenuJsonobject,list,Integer.parseInt(childrenMenu.get("id")+""));
            }
        }
        menu.put("children", childList);
    }
}
